package statter;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

public class Stats {
	private Hashtable<String, Vector<Stat>> stats;
	private long start = 0;
	private long end = 0;
	
	public Stats() {
		stats = new Hashtable<String, Vector<Stat>>();
		start = System.currentTimeMillis();
	}
	
	public void addSection(String name) {
		stats.put(name, new Vector<Stat>());
	}
	
	public void statStart(String sectionName) {
		stats.get(sectionName).add(new Stat());
	}
	
	public void statEnd(String sectionName) {
		stats.get(sectionName).get(stats.get(sectionName).size()-1).end();
	}
	
	public Enumeration<String> getSectionNames() {
		return stats.keys();
	}
	
	public Vector<Stat> getStats(String sectionName) {
		return stats.get(sectionName);
	}
	
	public long[] getTimes(String sectionName) {
		Vector<Stat> sectionStats = stats.get(sectionName);
		int size = sectionStats.size();
		long[] times = new long[size];
		for(int i = 0; i < size; i++) {
			long time = sectionStats.get(i).getTime();
			if (time != -1) {
				times[i] = time;
			}
		}			
		return times;
	}
	
	public long getAverage(String sectionName) {
		long[] times = getTimes(sectionName);
		if (times.length > 1) {
			long total = 0;
			for (int i = 0; i < times.length; i++) {
				total += times[i];
			}
			return total / times.length;
		}
		else if (times.length == 0) {
			return 0;
		}
		return times[0];
	}
	
	public int getExecuted(String sectionName) {
		Vector<Stat> sectionStats = stats.get(sectionName);
		return sectionStats.size();
	}
	
	public void printGlobalSectionStats(String sectionName) {
		System.out.println("-------------------------");
		System.out.println("Section name: " + sectionName);
		System.out.println("-------------------------");
		System.out.println("Executed: " + getExecuted(sectionName) + " times");
		System.out.println("Average time: " + getAverage(sectionName) + "ms");
		System.out.println();
	}
	
	public void printGlobalStats() {
		end = System.currentTimeMillis();
		System.out.println("Global stats:");
		System.out.println("-------------------------");
		System.out.println("Total time: " + (end - start));
		System.out.println("-------------------------");
		Enumeration<String> sectionNames = stats.keys();
		while (sectionNames.hasMoreElements()) {
			printGlobalSectionStats(sectionNames.nextElement());
		}
	}
}